/**
 * @description 使用dnd-kit实现react的拖拽功能
 * @author 大肘子
 */

import React, { FC } from "react";

//使用dnd-kit 需要的组件
import { DndContext, closestCenter, useSensor, useSensors, MouseSensor, DragEndEvent } from "@dnd-kit/core";
import { arrayMove, SortableContext, verticalListSortingStrategy } from "@dnd-kit/sortable";

//使用react的插槽

type propsType = {
  children: JSX.Element | JSX.Element[]; //插槽
  items: Array<{ id: string; [key: string]: any }>;
  onDragEnd: (oldIndex: number, newIndex: number) => void;
};

const SortTableContainer: FC<propsType> = (props) => {
  const { children, items, onDragEnd } = props;
  const sensors = useSensors(
    useSensor(MouseSensor, {
      activationConstraint: {
        distance: 8, //8px
      },
    }),
  );

  function handleDragEnd(event: DragEndEvent) {
    const { active, over } = event;
    if (over == null) return;
    const oldIndex = items.findIndex((c) => c.fe_id === active.id);
    const newIndex = items.findIndex((c) => c.fe_id === over.id);
    onDragEnd(oldIndex, newIndex);
  }

  return (
    <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
      <SortableContext items={items} strategy={verticalListSortingStrategy}>
        {children}
      </SortableContext>
    </DndContext>
  );
};

export default SortTableContainer;
